package com.castle.fortress.admin.member.service.impl;

import cn.hutool.core.util.StrUtil;

import com.castle.fortress.admin.member.dto.MemberDto;
import com.castle.fortress.admin.member.entity.MemberThumbsUpEntity;
import com.castle.fortress.admin.member.service.MemberThumbsUpService;
import com.castle.fortress.admin.utils.BizCommonUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.member.entity.MemberCommentEntity;
import com.castle.fortress.admin.member.dto.MemberCommentDto;
import com.castle.fortress.admin.member.mapper.MemberCommentMapper;
import com.castle.fortress.admin.member.service.MemberCommentService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.List;

/**
 * 会员评论表 服务实现类
 *
 * @author castle
 * @since 2023-02-20
 */
@Service
public class MemberCommentServiceImpl extends ServiceImpl<MemberCommentMapper, MemberCommentEntity> implements MemberCommentService {
    @Autowired
    private MemberThumbsUpService memberThumbsUpService;

    /**
     * 获取查询条件
     *
     * @param memberCommentDto
     * @return
     */
    public QueryWrapper<MemberCommentEntity> getWrapper(MemberCommentDto memberCommentDto) {
        QueryWrapper<MemberCommentEntity> wrapper = new QueryWrapper();
        if (memberCommentDto != null) {
            MemberCommentEntity memberCommentEntity = ConvertUtil.transformObj(memberCommentDto, MemberCommentEntity.class);
            wrapper.eq(memberCommentEntity.getId() != null, "id", memberCommentEntity.getId());
            wrapper.eq(StrUtil.isNotEmpty(memberCommentEntity.getCommentType()), "comment_type", memberCommentEntity.getCommentType());
            wrapper.eq(memberCommentEntity.getMemberId() != null, "member_id", memberCommentEntity.getMemberId());
            wrapper.eq(memberCommentEntity.getIsAnonymity() != null, "is_anonymity", memberCommentEntity.getIsAnonymity());
            wrapper.eq(memberCommentEntity.getTargetId() != null, "target_id", memberCommentEntity.getTargetId());
            wrapper.eq(memberCommentEntity.getParentId() != null, "parent_id", memberCommentEntity.getParentId());
            wrapper.like(StrUtil.isNotEmpty(memberCommentEntity.getParents()), "parents", memberCommentEntity.getParents());
            wrapper.like(StrUtil.isNotEmpty(memberCommentEntity.getContent()), "content", memberCommentEntity.getContent());
            wrapper.eq(memberCommentEntity.getCommentTime() != null, "comment_time", memberCommentEntity.getCommentTime());
            wrapper.eq(memberCommentEntity.getThumbsUpNum() != null, "thumbs_up_num", memberCommentEntity.getThumbsUpNum());
        }
        return wrapper;
    }


    @Override
    public IPage<MemberCommentDto> pageMemberComment(Page<MemberCommentDto> page, MemberCommentDto memberCommentDto) {
        QueryWrapper<MemberCommentEntity> wrapper = getWrapper(memberCommentDto);
        Page<MemberCommentEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        Page<MemberCommentEntity> memberCommentPage = baseMapper.selectPage(pageEntity, wrapper);
        Page<MemberCommentDto> pageDto = new Page(memberCommentPage.getCurrent(), memberCommentPage.getSize(), memberCommentPage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(memberCommentPage.getRecords(), MemberCommentDto.class));
        return pageDto;
    }


    @Override
    public List<MemberCommentDto> listMemberComment(MemberCommentDto memberCommentDto) {
        QueryWrapper<MemberCommentEntity> wrapper = getWrapper(memberCommentDto);
        List<MemberCommentEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list, MemberCommentDto.class);
    }

    @Override
    public IPage<MemberCommentDto> pageMemberCommentExtends(Page<MemberCommentDto> page, MemberCommentDto memberCommentDto, MemberDto member) {
        Map<String, Long> pageMap = BizCommonUtil.getPageParam(page);
        MemberCommentEntity memberCommentEntity = ConvertUtil.transformObj(memberCommentDto, MemberCommentEntity.class);
        List<MemberCommentDto> memberCommentDtos = ConvertUtil.transformObjList(baseMapper.extendsList(pageMap, memberCommentEntity), MemberCommentDto.class);
        List<Long> thumbsUp = new ArrayList<>();
        if (member != null) {
            QueryWrapper<MemberThumbsUpEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("type", "00");//评论
            wrapper.eq("member_id", member.getId());
            List<MemberThumbsUpEntity> thumbsUpEntities = memberThumbsUpService.list(wrapper);
            for (MemberThumbsUpEntity t : thumbsUpEntities) {
                thumbsUp.add(t.getTargetId());
            }
        }
        initThumbsUp(memberCommentDtos, thumbsUp);
        int sons = 2;
        //查询第一层回复
        List<Long> parentIds = new ArrayList<>();
        if (memberCommentDtos != null && memberCommentDtos.size() > 0) {
            memberCommentDtos.forEach(entity -> {
                parentIds.add(entity.getId());
            });
            List<MemberCommentDto> childers = ConvertUtil.transformObjList(baseMapper.childrens(parentIds), MemberCommentDto.class);
            initThumbsUp(childers, thumbsUp);
            for (MemberCommentDto dto : childers) {
                for (MemberCommentDto parent : memberCommentDtos) {
                    if (dto.getParentId().equals(parent.getId())) {
                        List<MemberCommentDto> c = parent.getChildren();
                        if (c == null) {
                            c = new ArrayList<>();
                            c.add(dto);
                        } else if (c.size() < sons) {
                            c.add(dto);
                        } else {
                            break;
                        }
                        parent.setChildren(c);
                        break;
                    }
                }
            }
        }
        Long total = baseMapper.extendsCount(memberCommentEntity);
        Page<MemberCommentDto> pageDto = new Page(page.getCurrent(), page.getSize(), total);
        pageDto.setRecords(ConvertUtil.transformObjList(memberCommentDtos, MemberCommentDto.class));
        return pageDto;
    }

    @Override
    public List<MemberCommentDto> treeByParentId(Long parentId, MemberDto member) {
        List<Long> thumbsUp = new ArrayList<>();
        if (member != null) {
            QueryWrapper<MemberThumbsUpEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("type", "00");//评论
            wrapper.eq("member_id", member.getId());
            List<MemberThumbsUpEntity> thumbsUpEntities = memberThumbsUpService.list(wrapper);
            for (MemberThumbsUpEntity t : thumbsUpEntities) {
                thumbsUp.add(t.getTargetId());
            }
        }
        Map<String, Object> params = new HashMap<>();
        params.put("parents", parentId);
//        QueryWrapper<MemberCommentEntity> wrapper = new QueryWrapper<>();
//        wrapper.like("parents",parentId);
//        wrapper.or().eq("id",parentId);
//        wrapper.orderByAsc("comment_time");
        List<MemberCommentDto> list = ConvertUtil.transformObjList(baseMapper.selectDataList(params), MemberCommentDto.class);
        initThumbsUp(list, thumbsUp);
        return ConvertUtil.listToTree(list);
    }

    @Override
    public List<MemberCommentDto> treeByTargetId(Long targetId, MemberDto member) {
        List<Long> thumbsUp = new ArrayList<>();
        if (member != null) {
            QueryWrapper<MemberThumbsUpEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("type", "00");//评论
            wrapper.eq("member_id", member.getId());
            List<MemberThumbsUpEntity> thumbsUpEntities = memberThumbsUpService.list(wrapper);
            for (MemberThumbsUpEntity t : thumbsUpEntities) {
                thumbsUp.add(t.getTargetId());
            }
        }
        Map<String, Object> params = new HashMap<>();
        params.put("targetId", targetId);
        List<MemberCommentDto> list = ConvertUtil.transformObjList(baseMapper.selectDataList(params), MemberCommentDto.class);
        initThumbsUp(list, thumbsUp);
        return ConvertUtil.listToTree(list);
    }

    @Override
    public boolean deleteByIdMemberComment(Long id) {

        try {
            baseMapper.deleteById(id);
            QueryWrapper<MemberCommentEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id", id);
            // 递归删除子评论
            baseMapper.delete(queryWrapper);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 初始化点赞数
     *
     * @param comments  评论记录
     * @param thumbsUps 点赞的评论ID集合
     */
    private void initThumbsUp(List<MemberCommentDto> comments, List<Long> thumbsUps) {
        if (comments != null && !comments.isEmpty() && thumbsUps != null && !thumbsUps.isEmpty()) {
            for (MemberCommentDto dto : comments) {
                if (thumbsUps.contains(dto.getId())) {
                    dto.setIsThumbsUp(true);
                }
            }
        }
    }
}

